<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .form-item {
            margin-bottom: 15px;
        }
        
        .form-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-item input, .form-item textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .form-item textarea {
            height: 80px;
            resize: vertical;
        }
        
        .btn-group {
            text-align: center;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 10px;
        }
        
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        
        .btn-default {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th, .table td {
            border: 1px solid #dcdfe6;
            padding: 12px;
            text-align: left;
        }
        
        .table th {
            background-color: #f5f7fa;
            font-weight: bold;
        }
        
        .table tr:hover {
            background-color: #f5f7fa;
        }
        
        .actions {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .edit-btn {
            background-color: #e6a23c;
            color: white;
        }
        
        .delete-btn {
            background-color: #f56c6c;
            color: white;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>用户管理</h2>
            <button class="btn btn-primary" onclick="showCreateForm()">创建用户</button>
        </div>
        
        <div class="card">
            <div id="loadingIndicator" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
            <table class="table" id="userTable" style="display: none;">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                    <!-- 数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <!-- 创建/编辑用户表单弹窗 -->
    <div id="userModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 1000;">
        <div class="card" style="width: 500px; margin: 100px auto; position: relative;">
            <h3 id="modalTitle">创建用户</h3>
            <form id="userForm">
                <input type="hidden" id="userId">
                <div class="form-item">
                    <label for="username">用户名</label>
                    <input type="text" id="username" required>
                </div>
                <div class="form-item">
                    <label for="password">密码</label>
                    <input type="password" id="password" required>
                </div>
                <div class="form-item">
                    <label for="email">邮箱</label>
                    <input type="email" id="email">
                </div>
                <div class="form-item">
                    <label for="userStatus">状态</label>
                    <select id="userStatus">
                        <option value="true">启用</option>
                        <option value="false">禁用</option>
                    </select>
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-default" onclick="hideModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    
    <script>
        // 当前编辑的用户ID
        let editingUserId = null;
        
        // 页面加载完成后获取用户列表
        document.addEventListener('DOMContentLoaded', function() {
            loadUsers();
            
            // 绑定表单提交事件
            document.getElementById('userForm').addEventListener('submit', saveUser);
        });
        
        // 显示加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const userTable = document.getElementById('userTable');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                userTable.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                userTable.style.display = 'table';
            }
        }
        
        // 获取用户列表
        async function loadUsers() {
            try {
                showLoading(true);
                const response = await fetch('/user/list', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const users = result.data || [];
                    renderUserTable(users);
                } else {
                    console.error('获取用户列表失败:', response.status);
                }
                showLoading(false);
            } catch (error) {
                console.error('获取用户列表异常:', error);
                showLoading(false);
            }
        }
        
        // 渲染用户表格
        function renderUserTable(users) {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = '';
            
            users.forEach(user => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.email || ''}</td>
                    <td>${user.status ? '启用' : '禁用'}</td>
                    <td>${new Date(user.createdAt).toLocaleString()}</td>
                    <td class="actions">
                        <button class="action-btn edit-btn" onclick="editUser(${user.id})">编辑</button>
                        <button class="action-btn delete-btn" onclick="deleteUser(${user.id})">删除</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }
        
        // 显示创建用户表单
        function showCreateForm() {
            editingUserId = null;
            document.getElementById('modalTitle').textContent = '创建用户';
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            document.getElementById('userModal').style.display = 'block';
        }
        
        // 编辑用户
        async function editUser(id) {
            try {
                const response = await fetch(`/user/${id}`, {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const user = await response.json();
                    editingUserId = user.id;
                    document.getElementById('modalTitle').textContent = '编辑用户';
                    document.getElementById('userId').value = user.id;
                    document.getElementById('username').value = user.username;
                    document.getElementById('password').value = ''; // 不显示密码
                    document.getElementById('email').value = user.email || '';
                    document.getElementById('userStatus').value = user.status;
                    document.getElementById('userModal').style.display = 'block';
                } else {
                    console.error('获取用户信息失败:', response.status);
                }
            } catch (error) {
                console.error('获取用户信息异常:', error);
            }
        }
        
        // 保存用户（创建或更新）
        async function saveUser(event) {
            event.preventDefault();
            
            const id = document.getElementById('userId').value;
            const userData = {
                username: document.getElementById('username').value,
                password: document.getElementById('password').value,
                email: document.getElementById('email').value,
                status: document.getElementById('userStatus').value === 'true'
            };
            
            // 如果是更新且密码为空，则不更新密码
            if (editingUserId && !userData.password) {
                delete userData.password;
            }
            
            try {
                let response;
                if (editingUserId) {
                    // 更新用户
                    response = await fetch(`/user/${editingUserId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(userData),
                        credentials: 'include'
                    });
                } else {
                    // 创建用户
                    response = await fetch('/user', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(userData),
                        credentials: 'include'
                    });
                }
                
                if (response.ok) {
                    hideModal();
                    loadUsers();
                } else {
                    console.error('保存用户失败:', response.status);
                }
            } catch (error) {
                console.error('保存用户异常:', error);
            }
        }
        
        // 删除用户
        async function deleteUser(id) {
            if (!confirm('确定要删除这个用户吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/user/${id}`, {
                    method: 'DELETE',
                    credentials: 'include'
                });
                
                if (response.ok) {
                    loadUsers();
                } else {
                    console.error('删除用户失败:', response.status);
                }
            } catch (error) {
                console.error('删除用户异常:', error);
            }
        }
        
        // 隐藏用户模态框
        function hideModal() {
            document.getElementById('userModal').style.display = 'none';
        }
    </script>
</body>
</html>